package com.dounine.clouddisk360.parser.deserializer.login;

import org.apache.http.client.ResponseHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.dounine.clouddisk360.parser.LoginParser;
import com.dounine.clouddisk360.parser.deserializer.BaseResponseHandle;
import com.dounine.clouddisk360.util.URLUtil;

public class LoginResponseHandle extends BaseResponseHandle<Login, LoginParser> implements ResponseHandler<Login> {
	private static final Logger LOGGER = LoggerFactory.getLogger(LoginResponseHandle.class);

	public LoginResponseHandle(LoginParser parse) {
		super(parse);
	}

	@Override
	public Login desializer(String result) {
		Login login = super.desializer(result);
		if(login.getErrno()!=0){
			return login;
		}
		parse.setBianaryFilename("user/userInfo.txt");
		parse.writeObjToDisk(login);
		return login;
	}

	@Override
	public String disassemblyResult(String result) {
		int userInfoIndex = result.indexOf(LoginConst.SPLIT_STR);
		if (userInfoIndex > -1) {
			String userInfo = result.substring(userInfoIndex + LoginConst.SPLIT_STR.length(),
					result.lastIndexOf(";</script>") - 2);
			return URLUtil.decode(userInfo);
		} else {
			StringBuffer sb = new StringBuffer();
			sb.append("{'errno':401,'errmsg':");
			String decodeResult = URLUtil.decode(result);
			if (decodeResult.contains("无效的登录")) {
				sb.append("'无效的登录'");
			} else if (decodeResult.contains("验证码错误请重新输入")) {
				sb.append("'验证码错误请重新输入'");
			} else {
				sb.append(result);
			}
			sb.append("}");
			return sb.toString();
		}
	}

	@Override
	public void saveCookie() {
		parse.getCookieStoreUT().writeCookieStoreToDisk(parse.getHttpClientContext().getCookieStore(),
				LoginConst.COOKIES_NAMES);
	}

}
